from flask import request, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from . import auth_bp
from ..services.auth_service import AuthService
from ..utils.response import success_response, error_response
from ..middlewares.permission import check_permission

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        if not data or not data.get('username') or not data.get('password'):
            return error_response(message="用户名和密码不能为空")
        
        result, message = AuthService.login(data['username'], data['password'])
        if result:
            return success_response(data=result, message=message)
        return error_response(message=message)
    except Exception as e:
        current_app.logger.error(f"登录失败: {str(e)}")
        return error_response(message="登录失败")

@auth_bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """用户登出"""
    try:
        # 这里可以添加token黑名单等逻辑
        return success_response(message="登出成功")
    except Exception as e:
        current_app.logger.error(f"登出失败: {str(e)}")
        return error_response(message="登出失败")

@auth_bp.route('/info', methods=['GET'])
@jwt_required()
def get_info():
    """获取当前用户信息"""
    try:
        user_id = get_jwt_identity()
        user_info = AuthService.get_user_info(user_id)
        if not user_info:
            return error_response(message="用户不存在", code=404)
        return success_response(data=user_info)
    except Exception as e:
        current_app.logger.error(f"获取用户信息失败: {str(e)}")
        return error_response(message="获取用户信息失败")

@auth_bp.route('/refresh-token', methods=['POST'])
@jwt_required(refresh=True)
def refresh_token():
    """刷新访问令牌"""
    try:
        user_id = get_jwt_identity()
        new_token = AuthService.refresh_token(user_id)
        return success_response(data=new_token)
    except Exception as e:
        current_app.logger.error(f"刷新令牌失败: {str(e)}")
        return error_response(message="刷新令牌失败")

# 错误处理
@auth_bp.errorhandler(Exception)
def handle_error(e):
    current_app.logger.error(f"认证错误: {str(e)}")
    return error_response(message="认证失败", code=401) 